package com.example.stockholdtrack.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.stockholdtrack.StockSearchResult
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.delay
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.util.concurrent.TimeUnit

class StockSearchViewModel : ViewModel() {
    
    private val _searchQuery = MutableStateFlow("")
    val searchQuery: StateFlow<String> = _searchQuery
    
    private val _searchResults = MutableStateFlow<List<StockSearchResult>>(emptyList())
    val searchResults: StateFlow<List<StockSearchResult>> = _searchResults
    
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading
    
    private val httpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .retryOnConnectionFailure(true)
        .build()
    
    init {
        // 监听搜索查询变化，实现防抖搜索
        viewModelScope.launch {
            searchQuery
                .debounce(500) // 500ms防抖
                .filter { it.length >= 2 } // 至少2个字符才开始搜索
                .distinctUntilChanged()
                .collect { query ->
                    searchStocks(query)
                }
        }
    }
    
    fun updateSearchQuery(query: String) {
        _searchQuery.value = query
        println("DEBUG: StockSearchViewModel.updateSearchQuery - 搜索查询更新: $query")
    }
    
    private suspend fun searchStocks(keyword: String) {
        if (keyword.isBlank()) {
            _searchResults.value = emptyList()
            return
        }
        
        _isLoading.value = true
        println("DEBUG: StockSearchViewModel.searchStocks - 开始搜索股票: $keyword")
        
        try {
            val results = performSearch(keyword)
            _searchResults.value = results
            println("DEBUG: StockSearchViewModel.searchStocks - 搜索完成，结果数量: ${results.size}")
        } catch (e: Exception) {
            println("DEBUG: StockSearchViewModel.searchStocks - 搜索失败: ${e.message}")
            _searchResults.value = emptyList()
        } finally {
            _isLoading.value = false
        }
    }
    
    private suspend fun performSearch(keyword: String): List<StockSearchResult> {
        return withContext(Dispatchers.IO) {
            val timestamp = System.currentTimeMillis()
            val callbackName = "jQuery${timestamp}_${(Math.random() * 1000000).toLong()}"
            
            val url = "https://search-codetable.eastmoney.com/codetable/search/web" +
                    "?client=web" +
                    "&clientType=webSuggest" +
                    "&clientVersion=lastest" +
                    "&cb=$callbackName" +
                    "&keyword=$keyword" +
                    "&pageIndex=1" +
                    "&pageSize=10" +
                    "&securityFilter=" +
                    "&_=$timestamp"
            
            println("DEBUG: StockSearchViewModel.performSearch - 请求URL: $url")
            
            try {
                println("DEBUG: StockSearchViewModel.performSearch - 开始执行网络请求")
                
                // 先测试一个简单的网络连接
                try {
                    println("DEBUG: StockSearchViewModel.performSearch - 测试网络连接...")
                    val testRequest = Request.Builder()
                        .url("https://www.baidu.com")
                        .build()
                    val testResponse = httpClient.newCall(testRequest).execute()
                    println("DEBUG: StockSearchViewModel.performSearch - 网络连接测试成功: ${testResponse.code}")
                } catch (e: Exception) {
                    println("DEBUG: StockSearchViewModel.performSearch - 网络连接测试失败: ${e.message}")
                    e.printStackTrace()
                }
                
                val request = Request.Builder()
                    .url(url)
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .addHeader("Referer", "https://www.eastmoney.com/")
                    .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                    .addHeader("Connection", "keep-alive")
                    .build()
                
                println("DEBUG: StockSearchViewModel.performSearch - 发送请求...")
                val response = httpClient.newCall(request).execute()
                println("DEBUG: StockSearchViewModel.performSearch - 收到响应: ${response.code}")
                
                if (!response.isSuccessful) {
                    throw Exception("HTTP请求失败: ${response.code} - ${response.message}")
                }
                
                val responseBody = response.body?.string()
                if (responseBody.isNullOrEmpty()) {
                    throw Exception("响应体为空")
                }
                
                println("DEBUG: StockSearchViewModel.performSearch - 原始响应长度: ${responseBody.length}")
                println("DEBUG: StockSearchViewModel.performSearch - 响应前100字符: ${responseBody.take(100)}")
                println("DEBUG: StockSearchViewModel.performSearch - 响应编码: ${response.body?.contentType()}")
                println("DEBUG: StockSearchViewModel.performSearch - 响应头: ${response.headers}")
                
                // 解析JSONP响应
                val jsonData = parseJsonpResponse(responseBody, callbackName)
                parseSearchResults(jsonData)
            } catch (e: Exception) {
                println("DEBUG: StockSearchViewModel.performSearch - 网络请求异常: ${e.message}")
                e.printStackTrace()
                throw e
            }
        }
    }
    
    private fun parseJsonpResponse(response: String, callbackName: String): String {
        try {
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - 开始解析JSONP响应")
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - 响应长度: ${response.length}")
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - 响应前200字符: ${response.take(200)}")
            
            // 移除JSONP回调函数包装
            val startIndex = response.indexOf("(")
            val endIndex = response.lastIndexOf(")")
            
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - 找到括号位置: startIndex=$startIndex, endIndex=$endIndex")
            
            if (startIndex == -1 || endIndex == -1 || startIndex >= endIndex) {
                println("DEBUG: StockSearchViewModel.parseJsonpResponse - 无效的JSONP响应格式")
                println("DEBUG: StockSearchViewModel.parseJsonpResponse - 响应内容: $response")
                throw Exception("无效的JSONP响应格式")
            }
            
            val jsonData = response.substring(startIndex + 1, endIndex)
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - 解析后的JSON数据长度: ${jsonData.length}")
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - JSON数据前100字符: ${jsonData.take(100)}")
            return jsonData
        } catch (e: Exception) {
            println("DEBUG: StockSearchViewModel.parseJsonpResponse - JSONP解析异常: ${e.message}")
            e.printStackTrace()
            throw e
        }
    }
    
    private fun parseSearchResults(jsonData: String): List<StockSearchResult> {
        try {
            val jsonObject = JSONObject(jsonData)
            println("DEBUG: StockSearchViewModel.parseSearchResults - JSON对象键: ${jsonObject.keys().asSequence().toList()}")
            
            if (!jsonObject.has("result")) {
                println("DEBUG: StockSearchViewModel.parseSearchResults - 响应中没有result字段")
                return emptyList()
            }
            
            val resultArray = jsonObject.getJSONArray("result")
            println("DEBUG: StockSearchViewModel.parseSearchResults - 结果数组长度: ${resultArray.length()}")
            
            val results = mutableListOf<StockSearchResult>()
            
            for (i in 0 until resultArray.length()) {
                try {
                    val item = resultArray.getJSONObject(i)
                    
                    // 只处理股票类型的结果
                    val securityTypeArray = item.getJSONArray("securityType")
                    var isStock = false
                    for (j in 0 until securityTypeArray.length()) {
                        if (securityTypeArray.getInt(j) == 2) { // 2表示股票
                            isStock = true
                            break
                        }
                    }
                    
                    if (isStock) {
                        val result = StockSearchResult(
                            code = item.getString("code"),
                            shortName = item.getString("shortName"),
                            securityTypeName = item.getString("securityTypeName"),
                            market = item.getInt("market"),
                            pinyin = item.getString("pinyin")
                        )
                        results.add(result)
                        println("DEBUG: StockSearchViewModel.parseSearchResults - 添加股票: ${result.shortName}(${result.code})")
                    }
                } catch (e: Exception) {
                    println("DEBUG: StockSearchViewModel.parseSearchResults - 解析第${i}个结果时异常: ${e.message}")
                }
            }
            
            println("DEBUG: StockSearchViewModel.parseSearchResults - 最终结果数量: ${results.size}")
            return results
        } catch (e: Exception) {
            println("DEBUG: StockSearchViewModel.parseSearchResults - 解析搜索结果异常: ${e.message}")
            throw e
        }
    }
} 